<template>
  <div class="cost-adjustment-container">
    <!-- 页面标题和操作按钮 -->
    <BasicInformation
      title="编辑库存调拨"
      :primary-actions="actions"
      @action="handleAction"
    />

    <!-- 表单 -->
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="120px"
    >
      <!-- 基础信息 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>

        <el-row :gutter="30">
          <el-col :md="12">
            <el-form-item label="编号" prop="code">
              <el-input v-model="form.code" clearable disabled />
            </el-form-item>
          </el-col>

          <el-col :md="12">
            <el-form-item label="单据日期" prop="date">
              <el perspective
                v-model="form.date"
                type="date"
                placeholder="请选择日期"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>

          <el-col :md="12">
            <el-form-item label="库管员" prop="skid">
              <el-select
                v-model="form.skid"
                placeholder="请选择库管员"
                style="width: 240px"
                clearable
                filterable
              >
                <el-option
                  v-for="user in userList"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 商品清单 -->
      <el-card class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">商品清单</span>
            <el-button
              type="primary"
              size="small"
              @click="goodsDialogVisible = true"
            >
              添加商品
            </el-button>
          </div>
        </template>

        <el-table :data="form.goods" border style="width: 100%">
          <el-table-column prop="code" label="商品编码" />
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="kname" label="商品分类" />
          <el-table-column prop="uname" label="商品单位" />
          <el-table-column prop="tax" label="税率" />
          <!-- 即时库存列 -->
          <el-table-column label="即时库存">
            <template #default="{ $index }">
              {{ stocks[$index] ?? '未选择仓库' }}
            </template>
          </el-table-column>
          <!-- 数量（最小1，最大库存） -->
          <el-table-column label="数量">
            <template #default="{ $index }">
              <el-input-number
                  v-model.number="form.counts[$index]"
                  :min="stocks[$index] > 0 ? 1 : 0"
                  :max="stocks[$index] ?? 0"
                  :step="1"
                  style="width: 100%"
                  @change="validateRowCount($index)"
                />
              <span v-if="stocks[$index] !== undefined" class="stock-hint">
                （当前库存：{{ stocks[$index] }}）
              </span>
            </template>
          </el-table-column>
          <!-- 出仓仓库 -->
          <el-table-column label="出仓仓库">
            <template #default="{ $index }">
              <el-select
                v-model="form.osids[$index]"
                placeholder="请选择出仓仓库"
                filterable
              >
                <el-option
                  v-for="wh in warehouses"
                  :key="wh.id"
                  :label="wh.name"
                  :value="wh.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <!-- 入仓仓库 -->
          <el-table-column label="入仓仓库">
            <template #default="{ $index }">
              <el-select
                v-model="form.isids[$index]"
                placeholder="请选择入仓仓库"
                filterable
              >
                <el-option
                  v-for="wh in warehouses"
                  :key="wh.id"
                  :label="wh.name"
                  :value="wh.id"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 商品选择对话框 -->
      <MaterialSelectorDialog
        v-model:modelValue="form.goods"
        v-model:visible="goodsDialogVisible"
      />
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { ProMove, Good } from '@/types/kc/KCDB'
import BasicInformation from '@/public-view/BasicInformation.vue'
import MaterialSelectorDialog from '@/basic-view/bom/MaterialSelectorDialog.vue'
import type { User } from '@/types/rs/User.ts'
import request from '@/util/request'

// 路由相关
const route = useRoute()
const router = useRouter()

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;

// 用户列表（库管员）
const userList = ref<User[]>([])
async function selectUser() {
  try {
    const response = await request.post('/per/user/getAll')
    userList.value = response.data.data
  } catch (error) {
    console.error('获取用户列表失败', error)
  }
}
selectUser()

// 表单数据
const form = reactive<Partial<ProMove>>({
  id: 0,
  code: '',
  date: '',
  skid: 0,
  goods: [] as Good[],
  counts: [] as number[],
  osids: [] as number[],
  isids: [] as number[],
  delFlag: 0,
  createDate: '',
  typeId: 4,
    createUser: user.user.name,
  updateUser: user.user.name,
})

// 即时库存数据
const stocks = ref<number[]>([])

// 表单校验规则
const rules = reactive<FormRules>({
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  skid: [{ required: true, message: '请选择库管员', trigger: 'change' }]
})

const formRef = ref<FormInstance>()
const goodsDialogVisible = ref(false)
const warehouses = ref<{ id: number; name: string }[]>([])
const actions = [
  { name: 'save', label: '保存', type: 'primary' },
  { name: 'reset', label: '重置', type: 'warning' }
]

// 禁用未来日期
const disabledDate = (time: Date) => time.getTime() > Date.now()

// 获取路由中的 code 参数
const getCode = () => {
  const raw = route.params.code
  return Array.isArray(raw) ? raw[0] : raw || ''
}

// 加载编辑页面数据
async function loadData() {
  const code = getCode()
  if (!code) {
    ElMessage.error('无效编号')
    router.back()
    return
  }
  try {
    const resp = await request.get('kc/proMove/GetOneProMove', {
      params: { code }
    })
    if (resp.data.code === 200 || resp.data.code === '200') {
      const data: ProMove = resp.data.data
      // 确保所有字段正确回显
      Object.assign(form, {
        id: data.id || 0,
        code: data.code || '',
        date: data.date || '',
        skid: data.skid || 0,
        goods: data.goods || [],
        counts: data.counts || data.goods?.map(() => 1) || [],
        osids: data.osids || data.goods?.map(() => 0) || [],
        isids: data.isids || data.goods?.map(() => 0) || [],
        delFlag: data.delFlag || 0,
        createDate: data.createDate || '',
        createUser: data.createUser || '',
        typeId: data.typeId || 4
      })
      // 同步数组长度
      syncGoodsArrays()
      // 加载完成后获取即时库存
      await fetchStocks()
    } else {
      ElMessage.error(resp.data.message || '加载失败')
      router.back()
    }
  } catch (error) {
    ElMessage.error('加载异常')
    router.back()
  }
}

// 同步 goods 相关数组
function syncGoodsArrays() {
  const len = form.goods.length
  form.counts = Array.from({ length: len }, (_, i) => form.counts[i] ?? 1)
  form.osids = Array.from({ length: len }, (_, i) => form.osids[i] ?? 0)
  form.isids = Array.from({ length: len }, (_, i) => form.isids[i] ?? 0)
  stocks.value = Array.from({ length: len }, () => 0)
}

// 获取即时库存
async function fetchStocks() {
  stocks.value = await Promise.all(
    form.osids.map(async (osid, idx) => {
      if (!osid || !form.goods[idx]?.id) return 0 // 未选择仓库或无商品 ID
      try {
        const r = await request.get('kc/StoreGoodSummary/selectKcStoreGoodBySidCid', {
          params: { sid: osid, gid: form.goods[idx].id }
        })
        return r.data.data?.stock || 0
      } catch (error) {
        console.error(`获取商品 ${form.goods[idx]?.id} 库存失败`, error)
        return 0
      }
    })
  )
}

// 监听 goods 和 osids 变化
watch(
  () => form.goods,
  () => {
    syncGoodsArrays()
    fetchStocks()
  },
  { deep: true }
)

watch(() => form.osids.slice(), fetchStocks, { immediate: true })

// 校验单行数量
function validateRowCount(index: number) {
  const max = stocks.value[index] || 0
  if (form.counts[index] > max) {
    ElMessage.error(`第 ${index + 1} 行数量不能超过库存 ${max}`)
    form.counts[index] = max > 0 ? max : 1
  }
}

// 加载仓库列表
onMounted(async () => {
  try {
    const res = await request.get('basic/store/getAllStore')
    warehouses.value = res.data.data
  } catch (e) {
    console.error('加载仓库失败', e)
  }
  loadData()
})

// 路由参数变化时重新加载
watch(() => route.params.code, loadData)

// 处理操作
function handleAction(name: string) {
  if (name === 'save') submitForm()
  else loadData()
}

// 提交表单
async function submitForm() {
  // 校验数量
  if (form.counts.some(c => c < 1)) {
    ElMessage.error('所有商品的数量必须大于0')
    return
  }
  for (let i = 0; i < form.goods.length; i++) {
    if (form.counts[i] > (stocks.value[i] || 0)) {
      ElMessage.error(`第 ${i + 1} 行“${form.goods[i].name}”的调拨数量不能超过库存 ${stocks.value[i] || 0}`)
      return
    }
  }
  try {
    await formRef.value?.validate()
    const payload = JSON.parse(JSON.stringify(form))
    payload.createDate = form.createDate
    payload.createUser = form.createUser
    const resp = await request.post(
      'kc/proMove/updateProMove',
      payload,
      { headers: { 'Content-Type': 'application/json' } }
    )
    if (resp.data.code === '200' || resp.data.code === 200) {
      ElMessage.success('更新成功')
      router.back()
    } else {
      ElMessage.error(resp.data.message || '更新失败')
    }
  } catch (e) {
    ElMessage.error('网络异常')
  }
}
</script>

<style scoped>
.cost-adjustment-container {
  padding: 20px;
}
.form-section {
  margin-bottom: 20px;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.section-title {
  font-size: 16px;
  font-weight: 600;
}
</style>
